<?php

/**
 * @Author: wuchenge
 * @Date: 2020-12-05 15:05:25
 * @email: ligui0506@sina.com
 * @descript: 权限中间件
 */

namespace App\Http\Middleware;

use App\Http\Controllers\ApiController;
use App\Libraries\Token as JwtToken;
use App\Models\Admin;
use App\Models\Rbac\Node;
use App\Services\Permission;
use Closure;
use Illuminate\Routing\Route;

class Rbac extends ApiController
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $name    = \Route::currentRouteName();
        $in_node = Node::where('name', $name)->first();

        // 拿到用户
        $user = JwtToken::authToken(Admin::class);
        \Log::debug($user);
        if (!$user) {
            return $this->setErrorCode(100401)->response();
        }

        $mid_params = ['admin_id' => $user->id];
        $request->attributes->add($mid_params); //添加参数

        // 不在则跳过
        if (!$in_node) {
            return $next($request);
        }

        // 获取当前用户的权限
        $permissions = Permission::getNodeBy($user->id);
        // 转成一维数组
        $permissions = array_values(reduceArray($permissions));

        $flag = false;
        foreach ($permissions as $value) {
            if ($name === $value) {
                $flag = true;
                break;
            }
        }
        if (!$flag) {
            return $this->setErrorCode(100401)->response();
        }

        return $next($request);
    }
}
